from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch

import utils
import logging
import urllib
import settings
import cgi


class Room(db.Model):
    name          = db.StringProperty()
    secret        = db.StringProperty()
    channel_id    = db.StringProperty()
    event_key     = db.StringProperty()
    destroy_key   = db.StringProperty()
    logged_users  = db.ListProperty(unicode)
    last_event_id = db.IntegerProperty()
    events        = db.ListProperty(unicode)
    added         = db.DateTimeProperty(auto_now_add=True)
    modified      = db.DateTimeProperty(auto_now=True)


class ListRoomsSingleton(db.Model):
    secret        = db.StringProperty()
    channel_id    = db.StringProperty()
    event_key     = db.StringProperty()
    destroy_key   = db.StringProperty()
    last_event_id = db.IntegerProperty()
    events        = db.ListProperty(unicode)
    added_time    = db.DateTimeProperty()
    checked_time  = db.DateTimeProperty()

    @staticmethod
    def get_singleton():
        s = ListRoomsSingleton.all().fetch(1)
        if len(s) < 1:
            s           = ListRoomsSingleton()
            s.secret    = utils.random_string()
            s.channel_id = 'notset'
            s.last_event_id = 0
            s.save()
            s = ListRoomsSingleton.all().fetch(1)
            assert s
        s = s[0]
        return s

